<template>
    <div class="" v-if="state !== 'hidden'">
        <el-form
            ref="form"
            :model="form"
            :label-width="'write' == state ? '115px' : 'auto'"
            :class="'write' == state ? 'write-form' : 'read-form'"
            :label-position="'write' == state ? 'top' : 'left'"
        >
            <div class="card-wrap flex-column justify-end card-padding">
                <div class="card-title-wrap">
                    <span>车辆信息</span>
                    <span></span>
                </div>

                <CarBaseInfo :form="form"></CarBaseInfo>
            </div>

            <div class="card-wrap flex-column justify-end card-padding">
                <div class="card-title-wrap">
                    <span>GPS维修信息</span>
                    <span></span>
                </div>

                <el-row :gutter="30">
                    <el-col :span="8">
                        <el-form-item label="GPS服务期限:" prop="expireGpsBrand">
                            <el-input v-if="'write' == state" v-model="servicePeriod" disabled></el-input>
                            <span v-else>{{ servicePeriod|filterNull }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="30">
                    <el-col :span="8">
                        <el-form-item label="GPS品牌:" prop="gpsBrand">
                            <el-input maxlength="50"
                                      v-model="form.gpsBrand"
                                      clearable
                                      v-if="'write' == state"
                                      placeholder="请输入GPS品牌"
                            ></el-input>
                            <span v-else>{{ form.gpsBrand | filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="设备类型:" prop="equipmentType">
                            <el-select filterable
                                       @change="epTypeSel"
                                       v-if="'write' == state"
                                       v-model="form.equipmentType"
                                       clearable
                                       style="width: 100%"
                            >
                                <template
                                    v-for="dict in dict.type.gps_device_type"
                                >
                                    <el-option
                                        :label="dict.label"
                                        :value="dict.value"
                                        :key="dict.value"
                                    ></el-option>
                                </template>
                            </el-select>
                            <span v-else
                            ><dict-tag
                                :options="dict.type.gps_device_type"
                                :value="form.equipmentType"
                            /></span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="设备编号:" prop="equipmentNo"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择设备编号',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.equipmentNo, callback)
                                       }:{}">

                            <el-input maxlength="100"
                                      v-model="form.equipmentNo"
                                      clearable disabled
                                      v-if="'write' == state"
                                      placeholder="请输入设备编号"
                            ></el-input>

<!--                            <el-select filterable-->
<!--                                       @change="equipSel"-->
<!--                                       v-if="'write' == state" v-model="form.equipmentNo" clearable style="width: 100%">-->
<!--                                <template v-for="dict in simList">-->
<!--                                    <el-option :label="dict.equipmentNo" :value="dict.equipmentNo"-->
<!--                                               :key="dict.equipmentNo"></el-option>-->
<!--                                </template>-->
<!--                            </el-select>-->
                            <span v-else>
                                {{ form.equipmentNo|filterNull }}

                            </span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="SIM卡号:" prop="sim"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择SIM卡号',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.sim, callback)
                                       }:{}">
                            <el-input maxlength="100"
                                      v-model="form.sim"
                                      clearable disabled
                                      v-if="'write' == state"
                                      placeholder="请输入SIM卡号"
                            ></el-input>

<!--                            <el-select filterable-->
<!--                                       @change="simSel"-->
<!--                                       v-if="'write' == state" v-model="form.sim" clearable style="width: 100%">-->
<!--                                <template v-for="dict in simList">-->
<!--                                    <el-option :label="dict.simNo" :value="dict.simNo" :key="dict.simNo"></el-option>-->
<!--                                </template>-->
<!--                            </el-select>-->
                            <span v-else>
                                {{ form.sim|filterNull }}

                            </span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item
                            label="预约维修时间:"
                            prop="maintenanceTime"
                            :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请选择预约维修时间',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.maintenanceTime,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
                        >
                            <el-date-picker
                                v-model="form.maintenanceTime"
                                style="width: 100%"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                v-if="'write' == state"
                                type="datetime"
                                placeholder="请选择预约维修时间"
                            ></el-date-picker>
                            <span v-else>{{
                                    form.maintenanceTime | filterNull
                                }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item
                            label="维修费用:"
                            prop="maintenancePrice"
                            :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请输入维修费用',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.maintenancePrice,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
                        >
                            <el-input
                                v-model="form.maintenancePrice"
                                clearable
                                v-if="'write' == state"
                                @input="value=>{if(isNaN(form.maintenancePrice)) { form.maintenancePrice = '' }; if(form.maintenancePrice.indexOf('.')>0){form.maintenancePrice=form.maintenancePrice.slice(0,form.maintenancePrice.indexOf('.')+3)} form.maintenancePrice = form.maintenancePrice.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                placeholder="请输入维修费用"
                            ></el-input>
                            <span v-else>{{
                                    form.maintenancePrice | filterNull
                                }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item
                            label="故障问题:"
                            prop="faultIssues"
                            :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请输入故障问题',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.faultIssues,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
                        >
                            <el-input maxlength="50"
                                      v-model="form.faultIssues"
                                      clearable
                                      v-if="'write' == state"
                                      placeholder="请输入故障问题"
                            ></el-input>
                            <span v-else>{{
                                    form.faultIssues | filterNull
                                }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item
                            label="维修地点:"
                            prop="maintenanceAddress"
                            :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请输入维修地点',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.maintenanceAddress,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
                        >
<!--                            <el-input maxlength="50"-->
<!--                                      v-model="form.maintenanceAddress"-->
<!--                                      clearable-->
<!--                                      v-if="'write' == state"-->
<!--                                      placeholder="请输入维修地点"-->
<!--                            ></el-input>-->
                            <ProvinceCityDistrict v-if="'write' == state"
                                                  placeholder="请选择维修地点" v-model="form.maintenanceAddressCode"
                                                  @change="citySelectionChange"></ProvinceCityDistrict>
                            <span v-else>{{
                                    form.maintenanceAddress | filterNull
                                }}</span>
                        </el-form-item>
                    </el-col>

                  <el-col :span="8">
                    <el-form-item
                      label="维修详细地点:"
                      prop="maintenanceAddressInfo"
                      :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请输入维修详细地点',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.maintenanceAddressInfo,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
                    >
                      <el-input maxlength="50"
                                v-model="form.maintenanceAddressInfo"
                                clearable
                                v-if="'write' == state"
                                placeholder="请输入维修详细地点"
                      ></el-input>
                      <span v-else>{{
                          form.maintenanceAddressInfo | filterNull
                        }}</span>
                    </el-form-item>
                  </el-col>

                    <el-col :span="8">
                        <el-form-item
                            label="现场联系人:"
                            prop="sceneContacts"
                            :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请输入现场联系人',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.sceneContacts,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
                        >
                            <el-input maxlength="50"
                                      v-model="form.sceneContacts"
                                      clearable
                                      v-if="'write' == state"
                                      placeholder="请输入现场联系人"
                            ></el-input>
                            <span v-else>{{
                                    form.sceneContacts | filterNull
                                }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item
                            label="现场联系电话:"
                            prop="sceneContactsTel"
                            :rules="
                                'write' == state
                                    ? [{
                                          required: true,
                                          message: '请输入现场联系电话',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.sceneContactsTel,
                                                  callback
                                              ),
                                      }, { pattern:  /^1[3456789]\d{9}$/, message: '联系电话格式不正确', trigger: 'blur' }]
                                    : {}
                            "
                        >
                            <el-input
                                v-model="form.sceneContactsTel"
                                clearable maxlength="11"
                                v-if="'write' == state"
                                @input="value=>form.sceneContactsTel=value.replace(/[^\d]/g,'')"
                                placeholder="请输入现场联系电话"
                            ></el-input>
                            <span v-else>{{
                                    form.sceneContactsTel | filterNull
                                }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>
            <div class="card-wrap flex-column justify-end card-padding">
                <div class="card-title-wrap">
                    <span>备注</span>
                    <span></span>
                </div>
                <el-row :gutter="30">
                    <el-col :span="24">
                        <el-form-item
                            label="上传照片:"
                            prop="imageOss"
                            style="width: 100%"
                        >
                            <ImageCommon
                                :disabled="'write' != state"
                                :up-type="2"
                                info="选择附件"
                                :limit="9"
                                v-model="form.imageOss"
                            ></ImageCommon>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item
                            label="备注:"
                            prop="remark"
                            :rules="
                                'write' == state
                                    ? {
                                          required: 2 == form.renewFlag,
                                          message: '请输入备注',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.remark,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
                        >
                            <el-input maxlength="500"
                                      v-if="'write' == state"
                                      type="textarea"
                                      v-model="form.remark"
                                      clearable
                                      placeholder="请输入备注"
                            ></el-input>
                            <span v-else>{{ form.remark | filterNull }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>
        </el-form>
    </div>
</template>

<script>
import moment from "moment";
import CarBaseInfo from "@/views/GPSManage/components/carBaseInfo.vue";
import {gpsSimInfo} from "@/api/gps/gpsList";
import ProvinceCityDistrict from "@/components/ProvinceCityDistrict/index.vue";

export default {
    components: {ProvinceCityDistrict, CarBaseInfo},
    dicts: [
        "gps_workorder_status",
        "quota_rent_type",
        "gps_workorder_type",
        "gps_device_type",
        "gps_is_renewal",
    ],
    props: {
        value: {
            default: {},
        },
        state: {
            default: "write",
        },
    },
    computed: {
        form: {
            get() {
                return this.value;
            },
            set(value) {
                this.$emit("input", value);
            },
        }
    },
    watch: {
        form: {
            immediate: true,
            deep: true,
            handler(val) {
                if (this.firstEnter && val && val.carId) {
                    this.firstEnter = false
                    this.getSim()
                }
            }
        }
    },
    data() {
        return {
            simList: [],
            firstEnter: true,
            renewYearList: [
                {
                    label: "1年",
                    value: 1,
                },
                {
                    label: "2年",
                    value: 2,
                },
                {
                    label: "3年",
                    value: 3,
                },
                {
                    label: "4年",
                    value: 4,
                },
                {
                    label: "5年",
                    value: 5,
                },
            ],
            servicePeriod: ''
        };
    },
    mounted() {
        this.$nextTick(() => {
            if ("write" == this.state) {
                this.form.imageOss = "";
            }
        });
    },
    methods: {
      epTypeSel(val) {
        if (1 == val) {
          let finds = this.simList.filter(item => item.equipmentNo.indexOf("有线") >= 0);
          this.form.sim = finds?.map(item => item.simNo).join(",");
          this.form.equipmentNo = finds?.map(item => item.equipmentNo).join(",");
        } else if (2 == val) {
          let finds = this.simList.filter(item => item.equipmentNo.indexOf("无线") >= 0);
          this.form.sim = finds?.map(item => item.simNo).join(",");
          this.form.equipmentNo = finds?.map(item => item.equipmentNo).join(",");
        } else if (3 == val) {
          let finds = this.simList.filter(item => item.equipmentNo.indexOf("有线") >= 0 || item.equipmentNo.indexOf("无线") >= 0);
          this.form.sim = finds?.map(item => item.simNo).join(",");
          this.form.equipmentNo = finds?.map(item => item.equipmentNo).join(",");
        } else {
          this.form.sim = null
          this.form.equipmentNo = null
        }
      },
        citySelectionChange(val) {
          if (val.length > 0) {
            this.form.maintenanceAddressCode = val[0]?.path?.join(",")??""
            this.form.maintenanceAddress = val[0]?.parent?.parent?.label + val[0]?.parent?.label + val[0].label
          } else {
            this.form.maintenanceAddressCode = ""
            this.form.maintenanceAddress = null
          }

          this.$forceUpdate()
          this.$refs.form.validateField(["maintenanceAddress"]);
          this.$nextTick(()=>{
            this.$refs.form.validateField(["maintenanceAddress"]);
          })

        },
        equipSel(val) {
            let find = this.simList.find(item => item.equipmentNo == val);
            if (find) {
                this.form.sim = find.simNo
            } else {
                this.form.sim = null
            }
        },
        simSel(val) {
            let find = this.simList.find(item => item.simNo == val);
            if (find) {
                this.form.equipmentNo = find.equipmentNo
            } else {
                this.form.equipmentNo = null
            }
        },
        getSim() {
            gpsSimInfo({
                carId: this.form.carId
            }).then(res => {

                console.log('---', parseInt("3年", 10))
                this.servicePeriod = this.calculateServicePeriod(res?.data[0]?.installTime??'', res?.data[0]?.gpsServicePeriod??'');
                // installTime  gpsServicePeriod
                // this.servicePeriod = res?.data[0]?installTime:gpsServicePeriod
                this.simList = res?.data[0]?.equipmentNo?.split(",")?.map((item, index) => {

                    let simList = res?.data[0]?.simNo?.split(",");

                    return {
                        simNo: simList[index],
                        equipmentNo: item,
                    }

                }) ?? []
            })
        },

        calculateServicePeriod(installTime, gpsServicePeriod) {
            // 使用 moment.js 进行日期处理
            const moment = require('moment');

            // 解析安装时间
            const installMoment = moment(installTime);

            // 解析保修期，提取数字部分，无论是否含有“年”字样
            const years = parseInt(gpsServicePeriod, 10);

            if (isNaN(years)) {
                return '无效的服务期限';
            }

            // 计算保修到期时间，不论字符串是否具有“年”字样都按年计算
            const serviceEndMoment = installMoment.add(years, 'years');

            // 获取当前时间
            const currentMoment = moment();

            // 比较当前时间与保修到期时间
            let servicePeriod = '';
            if (currentMoment.isBefore(serviceEndMoment)) {
                // 若当前时间在保修到期时间之前
                const remainingYears = serviceEndMoment.diff(currentMoment, 'years');
                // servicePeriod = `${remainingYears}年-质保期内`;
                servicePeriod = `${years}年-质保期内`;
            } else {
                // 若当前时间在保修到期时间之后
                const elapsedYears = currentMoment.diff(serviceEndMoment, 'years');
                // servicePeriod = `${elapsedYears}年-质保期外`;
                servicePeriod = `${years}年-质保期外`;
            }

            return servicePeriod;
        },

        renewSel(val) {
            if (this.form.renewYear && this.form.renewStartTime) {
                let endtime = moment(
                    this.form.renewStartTime,
                    "YYYY-MM-DD HH:mm:ss"
                )
                    .add(this.form.renewYear, "year")
                    .format("YYYY-MM-DD HH:mm:ss");
                this.$set(this.form, "renewEndTime", endtime);
            }
            this.$forceUpdate();
        },
        startChange(val) {
            if (this.form.renewYear && this.form.renewStartTime) {
                let endtime = moment(
                    this.form.renewStartTime,
                    "YYYY-MM-DD HH:mm:ss"
                )
                    .add(this.form.renewYear, "year")
                    .format("YYYY-MM-DD HH:mm:ss");
                this.$set(this.form, "renewEndTime", endtime);
            }
            this.$forceUpdate();
        },

        validData(rule, value, callback) {
            // console.log('aaa', rule, value, callback)
            if (rule.required && !value) {
                // this.$modal.msgError(`未填写${value}`);
                callback(new Error(rule.message));
            } else {
                callback();
            }
        },

        async valid() {
            // if(this.form.carList && this.form.carList.length>0){
            //     this.form.carIds = this.form.carList.map(item=>{
            //         return item.carId
            //     })
            //     this.form.workIds = this.form.carList.map(item=>{
            //         return item.id
            //     })
            // }else {
            //     this.form.carIds = [this.form.carId]
            //     this.form.workIds = [this.form.id]
            // }
            this.form.workId = this.form.id;

            return new Promise((resolve) => {
                if ('write' == this.state) {
                    this.$refs["form"].validate(valid => {
                        resolve(valid);
                    });
                } else {
                    resolve(true)
                }
            });
        },
    },
};
</script>

<style lang="scss" scoped>
::v-deep .el-form--label-top .el-form-item__label {
    padding: 0;
}

::v-deep .read-form .el-form-item__label-wrap,
::v-deep .read-form .el-form-item__content {
    margin-left: 0 !important;
}

.el-descriptions {
    margin: 0 -15px;
}
</style>
